import re
import sys
import os

def render_test_file(main_file_name):
        
    with open(main_file_name, encoding='utf8') as f:
        main_file = f.read()

    # 把引用替换为文件内容
    import_files = ['stock_select_methods', 'turtle_system', 'securities_info']
    for file_name in import_files:

        a = main_file.find(file_name)
        if a > 0:
            file_tmp = open(file_name + '.py', 'r', encoding='utf8').read()
            file_tmp = re.sub("\\\\", "\\\\\\\\", file_tmp) #处理 "\"
            file_tmp = clean_file(file_tmp)
            main_file= re.sub("(from|import).*?" + file_name + ".*?\n", "\n" + file_tmp + "\n", main_file)

    with open('_' + main_file_name, 'w', encoding='utf8') as f:
        r = f.write(main_file)
        # print(r)

    print("OK")

def clean_file(file_content):
    # 去掉 其他引用
    import_files = ['jqdata', 'join_quant_utils', 'securities_info']
    for file_name in import_files:

        a = file_content.find(file_name)
        if a >= 0:
            file_content, n= re.subn("(from|import).*?" + file_name + ".*?\n", "", file_content)
    
    return file_content


if __name__ == '__main__':
    # main_file_name = 'strategey_001_stock_peg_turtle.py'
    main_file_name = 'strategy_002_future_turtle.py'

    if len(sys.argv) >= 2:
        main_file_name = sys.argv[1]
        if os.path.isfile(main_file_name) == False:
            raise ValueError("File does not exist: " + main_file_name)
    else:
        # print(sys.argv)
        pass
            
    print("rendering jq backtest file: _" + main_file_name)
    render_test_file(main_file_name)